package com.jzo2o.market.handler;

import com.jzo2o.api.customer.CommonUserApi;
import com.jzo2o.api.customer.dto.response.CommonUserResDTO;
import com.jzo2o.common.utils.IdUtils;
import com.jzo2o.market.constants.RedisConstants;
import com.jzo2o.market.enums.CouponStatusEnum;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.redis.handler.SyncProcessHandler;
import com.jzo2o.redis.model.SyncMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ghy
 * @version V1.0
 * @date 2024/08/09
 **/
@Component(RedisConstants.RedisKey.COUPON_SEIZE_SYNC_QUEUE_NAME)
@Slf4j
public class SeizeCouponSyncProcessHandler implements SyncProcessHandler<Object> {

    @Resource
    private IActivityService activityService;
    @Resource
    private ICouponService couponService;
    @Resource
    private CommonUserApi commonUserApi;


    @Override
    public void batchProcess(List<SyncMessage<Object>> multiData) {
        throw new RuntimeException("不支持批量处理");
    }

    @Override
    public void singleProcess(SyncMessage<Object> singleData) {
        log.info("获取要同步抢券结果数据:{}",singleData);
        //用户ID
       long userId = Long.parseLong(singleData.getKey());
       //活动ID
       long activityId = Long.parseLong((String) singleData.getValue());
       log.info("userId={},活动Id={}",userId,activityId);
       //获取活动
       Activity activity = activityService.getById(activityId);
       if (activity == null){
           return;
       }
        CommonUserResDTO user = commonUserApi.findById(userId);
       if (user == null){
           return;
       }
        //新增优惠券
        Coupon coupon = new Coupon();
        coupon.setId(IdUtils.getSnowflakeNextId());
        coupon.setName(activity.getName());
        coupon.setUserId(userId);
        coupon.setUserName(user.getNickname());
        coupon.setUserPhone(user.getPhone());
        coupon.setActivityId(activityId);
        coupon.setType(activity.getType());
        coupon.setDiscountRate(activity.getDiscountRate());
        coupon.setDiscountAmount(activity.getDiscountAmount());
        coupon.setAmountCondition(activity.getAmountCondition());
        coupon.setValidityTime(LocalDateTime.now().plusDays(activity.getValidityDays()));
        coupon.setStatus(CouponStatusEnum.NO_USE.getStatus());
        //新增优惠券同步信息
        couponService.save(coupon);
        //扣减库存
        activityService.deductStock(activityId);
    }
}
